package org.sjs.dreamfly.biz.shortvideo

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.sjs.dreamfly.network.RetrofitUtil
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.model.VideoInfo
import org.sjs.dreamfly.network.api.HaoKanApi
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.atomic.AtomicBoolean

class ShortVideoViewModel : ViewModel() {

    private val videoList = mutableListOf<VideoInfo>()
    private var isLoading: AtomicBoolean = AtomicBoolean(false)
    suspend fun loadData(): MutableList<VideoInfo> = withContext(Dispatchers.IO) {
        isLoading.set(true)
        try {
            val response = RetrofitUtil.getHaoKanRetrofit().create(HaoKanApi::class.java).loadVideoList().execute()
            response.body()?.data?.list?.filter { it.videoSrc?.isNotEmpty()?:false }?.let {
                it.forEach { item ->
                    videoList.add(item.toVideoInfo())
                }
            }
            LogUtil.d("${response.isSuccessful}")
            isLoading.set(false)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return@withContext videoList
    }

    fun getVideoList(): MutableList<VideoInfo> {
        return videoList
    }

    fun loadMore(callback: () -> Unit?) {
        if (isLoading.get()) return
        LogUtil.d("before size: ${videoList.size}")
        MainScope().launch {
            loadData()
            LogUtil.d("after size: ${videoList.size}")
            callback()
        }
    }
}